//
//  BrowseAlbumController.m
//  OnionHome
//
//  Created by fengjie on 2019/9/30.
//  Copyright © 2019 FengJie. All rights reserved.
//

#import "BrowseAlbumController.h"

@interface BrowseAlbumController ()<UICollectionViewDelegate,UICollectionViewDataSource>
/**<#属性#>*/
@property (nonatomic,strong)UICollectionView*listView;
/**<#属性#>*/
@property (nonatomic,strong) UICollectionViewFlowLayout * layout;

/**选择个数*/
@property (nonatomic,strong)UILabel*seleNumLabel;
@end

@implementation BrowseAlbumController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createNavView];
    self.automaticallyAdjustsScrollViewInsets = NO;
//    self.view.backgroundColor = UIColorFromRGB(0x363647);
    
    [self.view addSubview:self.listView];
    
    [self.listView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setNavBarBackgroundAndClearColor];
    [UIApplication sharedApplication].statusBarHidden = YES;
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self setNavBarBackgroundAndNotClearColor];
    [UIApplication sharedApplication].statusBarHidden = NO;
}
-(void)createNavView{
    UIView * rightView = UIView.new;
    rightView.userInteractionEnabled = YES;
    [rightView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(rightAction)]];
    UIButton * commitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [commitBtn setTitle:@"完成" forState:UIControlStateNormal];
    commitBtn.titleLabel.font = SYSTEMFONT(16);
    kWeakSelf(weakSelf);
    [commitBtn addActionHandler:^{
        [weakSelf rightAction];
    }];
    
    [rightView addSubview:commitBtn];
    [rightView addSubview:self.seleNumLabel];
    
    [commitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.right.mas_equalTo(0);
    }];
    [self.seleNumLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.left.mas_equalTo(0);
        make.right.mas_equalTo(commitBtn.mas_left).offset(-5);
        make.width.height.mas_equalTo(16);
    }];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightView];
    
}
-(void)backBtnClicked{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)rightAction{
    BlockSafeRun(self.commitblock,self.albumModel);
    [self backBtnClicked];
}
-(void)setAlbumModel:(AlbumModel *)albumModel{
    _albumModel = albumModel;
    self.seleNumLabel.text = [NSString stringWithFormat:@"%lu",(unsigned long)albumModel.selectRows.count];

}
#pragma mark ---UICollectionViewDelegate,UICollectionViewDataSource
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.albumModel.assets.count ;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    BrowseAlbumCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass(BrowseAlbumCell.class) forIndexPath:indexPath];
    cell.row = indexPath.row ;
    cell.asset = self.albumModel.assets[indexPath.row];
    [cell loadImage:indexPath];
    cell.isSelect = [self.albumModel.selectRows containsObject:@(indexPath.row)];

    __weak typeof(self) weakSelf = self;
   __weak typeof(cell) weakCell = cell;
       cell.selectPhotoAction = ^(PHAsset *asset) {
           BOOL isReloadCollectionView = NO;
           if ([weakSelf.albumModel.selectRows containsObject:@(indexPath.row)]) {
               [weakSelf.albumModel.selectRows removeObject:@(indexPath.row)];
               [PhotoManger standardPhotoManger].choiceCount--;
               
               isReloadCollectionView = [PhotoManger standardPhotoManger].choiceCount == 9;
           } else {
               if ([PhotoManger standardPhotoManger].maxCount == [PhotoManger standardPhotoManger].choiceCount) {
                   return;
               }
               
               [weakSelf.albumModel.selectRows addObject:@(indexPath.row)];
               [PhotoManger standardPhotoManger].choiceCount++;
               isReloadCollectionView = [PhotoManger standardPhotoManger].choiceCount == 10;
           }
           
           if (isReloadCollectionView) {
               [weakSelf.listView reloadData];
           } else {
               weakCell.isSelect = [weakSelf.albumModel.selectRows containsObject:@(indexPath.row)];
           }
           self.seleNumLabel.text = [NSString stringWithFormat:@"%lu",(unsigned long)self.albumModel.selectRows.count];
       };
    return cell;
}
//cell将要出现的时候调用
-(void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
    DLogFunc;
    if (self.indexxPath) {
        [self.listView scrollToItemAtIndexPath:self.indexxPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
        self.indexxPath = nil;
    }
    
}
//cell离开tableView时调用
-(void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
    DLogFunc;
}
#pragma mark  定义每个cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(KScreenWidth,  KScreenHeight);
}
// 列间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}
// 行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

#pragma mark ---懒加载
-(UICollectionView *)listView{
    if (!_listView) {
        self.layout= [[UICollectionViewFlowLayout alloc] init];
        self.layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _listView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.layout];
        _listView.backgroundColor=KBlackColor;
        _listView.delegate=self;
        _listView.dataSource = self;
        _listView.scrollEnabled = YES;
        _listView.bounces = NO;
        _listView.pagingEnabled = YES;
        [_listView registerClass:[BrowseAlbumCell class] forCellWithReuseIdentifier:NSStringFromClass(BrowseAlbumCell.class)];
        if (@available(iOS 11.0, *)) {
            _listView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
    return _listView;
}

-(UILabel*)seleNumLabel{
    if(!_seleNumLabel){
        _seleNumLabel=[UILabel new];
        _seleNumLabel.textColor = KWhiteColor;
        _seleNumLabel.font = SYSTEMFONT(11);
        _seleNumLabel.textAlignment = NSTextAlignmentCenter;
        _seleNumLabel.text = @"0";
        ViewRadius(_seleNumLabel, 8);
        _seleNumLabel.userInteractionEnabled = YES;
        _seleNumLabel.backgroundColor = UIColorFromRGB(0x009966);
    }
    return _seleNumLabel;
}
@end


@interface BrowseAlbumCell ()
/// 相片
@property (nonatomic, strong) UIImageView *photoImageView;
/// 选中按钮
@property (nonatomic, strong) UIButton *selectButton;
@end


@implementation BrowseAlbumCell

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self photoImageView];
        [self selectButton];

    }
    return self;
}


#pragma mark - Set方法
-(void)setIsSelect:(BOOL)isSelect {
    _isSelect = isSelect;
    [self.selectButton setBackgroundImage:isSelect ? [UIImage imageNamed: @"selectImage_select"] : nil forState:UIControlStateNormal];    
}

#pragma mark - 加载图片
-(void)loadImage:(NSIndexPath *)indexPath {
    CGFloat imageWidth = KScreenWidth;
    self.photoImageView.image = nil;
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    // 同步获得图片, 只会返回1张图片
    options.synchronous = NO;
    
    [[PHCachingImageManager defaultManager] requestImageForAsset:self.asset targetSize:CGSizeMake(imageWidth * [UIScreen mainScreen].scale, imageWidth * [UIScreen mainScreen].scale) contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        if (self.row == indexPath.row) {
            self.photoImageView.image = result;
        }
    }];
}

#pragma mark - 点击事件
-(void)selectPhoto:(UIButton *)button {
    if (self.selectPhotoAction) {
        self.selectPhotoAction(self.asset);
    }
}

#pragma mark - Get方法
-(UIImageView *)photoImageView {
    if (!_photoImageView) {
        _photoImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, (KScreenHeight - KScreenWidth) /2, KScreenWidth , KScreenWidth)];
        _photoImageView.contentMode = UIViewContentModeScaleAspectFill;
        _photoImageView.layer.masksToBounds = YES;
        _photoImageView.userInteractionEnabled = YES;
        
        [self.contentView addSubview:_photoImageView];
    }
    
    return _photoImageView;
}

-(UIButton *)selectButton {
    if (!_selectButton) {
        _selectButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _selectButton.layer.borderColor = [UIColor whiteColor].CGColor;
        _selectButton.layer.borderWidth = 1.f;
        _selectButton.layer.cornerRadius = 10.0f;
        _selectButton.layer.masksToBounds = YES;
        [_selectButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_selectButton addTarget:self action:@selector(selectPhoto:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.contentView addSubview:_selectButton];
        _selectButton.frame = CGRectMake((KScreenWidth - 20.f) - 16 , KScreenHeight - 20 - 16, 20, 20);
    }
    
    return _selectButton;
}

@end
